import { app, BrowserWindow, shell } from "electron";
import { join } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";

const __filename = fileURLToPath(import.meta.url);
const __dirname = join(__filename, "..");

let mainWindow = null;

function createMainWindow() {
    const window = new BrowserWindow({
        width: 1200,
        height: 800,
        webPreferences: {
            nodeIntegration: false,
            contextIsolation: true,
            sandbox: true,
        },
    });

    if (process.env.ELECTRON_START_URL) {
        window.loadURL(process.env.ELECTRON_START_URL);
    } else {
        const indexPath = join(process.cwd(), "dist", "index.html");
        // window.loadURL(pathToFileURL(indexPath).toString());
        window.loadURL("http://localhost:5173/");
    }

    window.webContents.setWindowOpenHandler(({ url }) => {
        shell.openExternal(url);
        return { action: "deny" };
    });

    window.on("closed", () => {
        mainWindow = null;
    });

    return window;
}

app.whenReady().then(() => {
    mainWindow = createMainWindow();

    app.on("activate", () => {
        if (BrowserWindow.getAllWindows().length === 0) {
            mainWindow = createMainWindow();
        }
    });
});

app.on("window-all-closed", () => {
    if (process.platform !== "darwin") app.quit();
});
